package com.qixin.modules.eaLoan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qixin.modules.ea.entity.EaBookDetail;
import com.qixin.modules.ea.entity.EaTravel;
import com.qixin.modules.ea.vo.ListPageVo;
import com.qixin.modules.eaApplication.entity.EaBusinessApply;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaBasic.mapper.EaTaskMapper;
import com.qixin.modules.eaBasic.util.ChangeIdToNameUtil;
import com.qixin.modules.eaBasic.util.WorkFlowUtil;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import com.qixin.modules.eaBasic.vo.UserIdPageVo;
import com.qixin.modules.eaLoan.entity.EaLoanbill;
import com.qixin.modules.eaLoan.entity.EaLoanbillDetail;
import com.qixin.modules.eaLoan.mapper.EaLoanbillDetailMapper;
import com.qixin.modules.eaLoan.mapper.EaLoanbillMapper;
import com.qixin.modules.eaLoan.service.IEaLoanbillService;
import com.qixin.modules.eaLoan.service.IEaLoanbillServiceCopy;
import com.qixin.modules.rzInvoice.entity.EaBill;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 借款单
 * @Author: qixin-boot
 * @Date:   2021-07-20
 * @Version: V1.0
 */
@Service
public class EaLoanbillServiceImplCopy extends ServiceImpl<EaLoanbillMapper, EaLoanbill> implements IEaLoanbillServiceCopy {

	@Autowired
	private EaLoanbillMapper eaLoanbillMapper;
	@Autowired
	private EaLoanbillDetailMapper eaLoanbillDetailMapper;
	@Value(value = "${server.fileurl}")
	private String fileurl;
	@Autowired
	private EaTaskMapper eaTaskMapper;
	@Autowired
	private ChangeIdToNameUtil changeIdToNameUtil;
	@Autowired
	private WorkFlowUtil workFlowUtil;

	//新增借款单
	@Override
	@Transactional
	public Map<String,Object> saveMain(EaLoanbill eaLoanbill) {
		Map<String,Object> returnMap = new HashMap<String,Object>();
		Object result = FillRuleUtil.executeRule("LoanCodeRule", null);  //获取单据编号
		eaLoanbill.setBillNo(result.toString());

		String saveType = eaLoanbill.getSaveType();
		if(saveType.equals("add")) {  //add保存,send提交
			eaLoanbill.setState(0);   //单据状态:0未提交,1审批中,2已审批,3已退回
		}else{
			eaLoanbill.setState(1);   //单据状态:0未提交,1审批中,2已审批,3已退回
		}

		eaLoanbill.setId(Uuid32Util.getUUid());  //主键
		eaLoanbill.setIsused("0");
		eaLoanbillMapper.insert(eaLoanbill);

		//新增待办
		EaTask eaTask = new EaTask();
		eaTask.setId(Uuid32Util.getUUid());
		eaTask.setFormType("2");  //单据类型:1差旅费报销单,2借款单,3还款单,4出差申请单,5出差申请变更单,6招待费申请单,7招待费申请变更单,8招待费报销单,9资金支付审批单,10通讯报销单,11电话记录单
		eaTask.setAuditManId(eaLoanbill.getAuditManId());   //审批人id
		eaTask.setAuditMan(eaLoanbill.getAuditMan());    //审批人
		//提交类型:保存:add,提交:send
		if(saveType.equals("add")){  //add保存,send提交
			eaTask.setStatus("0");
		}else{
			eaTask.setStatus("1");
		}
		eaTask.setFormId(eaLoanbill.getId());    //单据id
		eaTask.setFormCode(eaLoanbill.getBillNo());   //单据编号
		eaTask.setMemo("");    //备注
		eaTask.setTotalFee(eaLoanbill.getLoanAmount()); //总金额
		eaTask.setSort("2");   //排序
		eaTask.setTitle("借款单");  //标题
		eaTask.setSendManId(eaLoanbill.getPersonId());    //发送人id
		eaTask.setSendMan(changeIdToNameUtil.getPsnNameById(eaLoanbill.getPersonId()));    //发送人
		eaTask.setSendDepartId(eaLoanbill.getDeptId());  //发送人部门id
		eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaLoanbill.getDeptId()));   //发送人部门
		eaTask.setSendTime(new Date());    //发送时间
		eaTaskMapper.insert(eaTask);

		returnMap.put("id",eaLoanbill.getId());
		returnMap.put("code","0");
		returnMap.put("message","保存成功!");
		return returnMap;
	}

	//编辑借款单
	@Override
	@Transactional
	public Map<String,Object> updateMain(EaLoanbill eaLoanbill) {
		Map<String,Object> returnMap = new HashMap<String,Object>();

		//如果picture中有http://localhost:9092/qixin-boot/aaa.png,要处理只保留文件名
		String picture = eaLoanbill.getPicture() != null ? eaLoanbill.getPicture().toString() : "";
		String picture_final = picture.replaceAll(fileurl,"");;
		//设置最终的图片如:1111.png,2222.png
		eaLoanbill.setPicture(picture_final);

		String saveType = eaLoanbill.getSaveType();
		if(saveType.equals("add")) {  //add保存,send提交
			EaLoanbill eaLoanbill1 = eaLoanbillMapper.selectById(eaLoanbill.getId());
			eaLoanbill.setState(eaLoanbill1.getState());   //单据状态:0未提交,1审批中,2已审批,3已退回
		}else{
			eaLoanbill.setState(1);   //单据状态:0未提交,1审批中,2已审批,3已退回
		}

		eaLoanbillMapper.updateById(eaLoanbill);

		//修改待办
		Map<String,Object> paramsMap2 = new HashMap<String,Object>();
		paramsMap2.put("form_id",eaLoanbill.getId());
		List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap2);
		for (EaTask eaTask:eaTaskList) {
			eaTask.setAuditManId(eaLoanbill.getAuditManId());   //审批人id
			eaTask.setAuditMan(eaLoanbill.getAuditMan());    //审批人
			//提交类型:保存:add,提交:send
			if(saveType.equals("add")){  //add保存,send提交
				eaTask.setStatus("0");
			}else{
				eaTask.setStatus("1");
			}
			eaTask.setFormId(eaLoanbill.getId());    //单据id
			eaTask.setFormCode(eaLoanbill.getBillNo());   //单据编号
			eaTask.setMemo("");    //备注
			eaTask.setTotalFee(eaLoanbill.getLoanAmount()); //总金额
			eaTask.setSendManId(eaLoanbill.getPersonId());    //发送人id
			eaTask.setSendMan(changeIdToNameUtil.getPsnNameById(eaLoanbill.getPersonId()));    //发送人
			eaTask.setSendDepartId(eaLoanbill.getDeptId());  //发送人部门id
			eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaLoanbill.getDeptId()));   //发送人部门
			eaTask.setSendTime(new Date());    //发送时间
			eaTaskMapper.updateById(eaTask);
		}

		returnMap.put("id",eaLoanbill.getId());
		returnMap.put("code","0");
		returnMap.put("message","编辑成功!");
		return returnMap;
	}

	@Override
	@Transactional
	public Map<String,Object> delMain(String id) {
		Map<String,Object> returnMap = new HashMap<String,Object>();
		EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(id);
		String isused = eaLoanbill.getIsused();  //是否被使用,1为已使用
		if(isused.equals("1")){
			returnMap.put("code","-1");
			returnMap.put("message","借款单:"+eaLoanbill.getBillNo() + "已被使用,不允许被删除!");
			return returnMap;
		}

		eaLoanbillDetailMapper.deleteByMainId(id);
		eaLoanbillMapper.deleteById(id);

		//删除相应的待办
		Map<String,Object> paramaMap = new HashMap<String,Object>();
		paramaMap.put("form_id",id);
		List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramaMap);
		if(eaTaskList != null && eaTaskList.size() > 0){
			EaTask eaTask = eaTaskList.get(0);

			//删除相应的工作流
			workFlowUtil.deleteWorkFlowById(eaTask.getWorkflowTaskId(),eaTask.getProcinstId());

			eaTaskMapper.deleteById(eaTask.getId());
		}

		returnMap.put("code","0");
		returnMap.put("message","删除成功!");
		return returnMap;
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			eaLoanbillDetailMapper.deleteByMainId(id.toString());
			eaLoanbillMapper.deleteById(id);
		}
	}

	//查询借款单列表
	@Override
	public Map<String, Object> list(ListPageVo listPageVo) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Map<String,Object> map = new HashMap<String,Object>();
		String page = EmptyUtil.checkNull(listPageVo.getPage());
		String limit = EmptyUtil.checkNull(listPageVo.getLimit());
		String keyword = EmptyUtil.checkNull(listPageVo.getKeyword());
		String userid = EmptyUtil.checkNull(loginUser.getId());   //用户id
		String isused = EmptyUtil.checkNull(listPageVo.getIsused());   //是否已使用
		String status = EmptyUtil.checkNull(listPageVo.getStatus());   //状态
		String billNo = EmptyUtil.checkNull(listPageVo.getBillNo());   //单据编号(pc)
		String billDateBegin = EmptyUtil.checkNull(listPageVo.getBillDateBegin());   //单据日期-开始(pc)
		String billDateEnd = EmptyUtil.checkNull(listPageVo.getBillDateEnd());   //单据日期-结束(pc)
		String personId = EmptyUtil.checkNull(listPageVo.getPersonId());   //申请人/报销人/借款人/还款人(pc)
		String explainStr = EmptyUtil.checkNull(listPageVo.getCasue());   //事由(pc)
		String addId = EmptyUtil.checkNull(listPageVo.getAddId());   //要多查询出来的发票id
		String sysOrgCode = EmptyUtil.checkNull(listPageVo.getSysOrgCode());   //所属组织
		String keyword1 = "%" + keyword + "%";
		map.put("keyword",keyword1);
		map.put("page",(Integer.parseInt(page) -1) * Integer.parseInt(limit));
		map.put("limit",Integer.parseInt(limit));
		map.put("userid",userid);
		map.put("isused",isused);
		map.put("status",status);
		map.put("billNo",billNo);
		map.put("billDateBegin",billDateBegin);
		map.put("billDateEnd",billDateEnd);
		map.put("personId",personId);
		map.put("explainStr",explainStr);
		map.put("sysOrgCode",sysOrgCode);
		if(!addId.equals("")){
			String[] addIds = addId.split(",");
			map.put("addId",addIds);
		}else{
			map.put("addId",addId);
		}
		List<EaLoanbill> eaLoanbillList = eaLoanbillMapper.selectLoanBills(map);

		List<Map<String,Object>> returnList = new ArrayList<Map<String,Object>>();
		if(eaLoanbillList != null && eaLoanbillList.size() > 0){
			for (int i = 0; i < eaLoanbillList.size(); i++) {
				Map<String,Object> returnMap = new HashMap<String,Object>();
				returnMap = JSON.parseObject(JSON.toJSONString(eaLoanbillList.get(i), SerializerFeature.WriteMapNullValue), Map.class);

				//格式化时间
				Long createTime = returnMap.get("createTime") != null ? Long.parseLong(returnMap.get("createTime").toString()) : null;
				String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
				returnMap.put("createTime",createTimeStr);

				//格式化时间
				Long updateTime = returnMap.get("updateTime") != null ? Long.parseLong(returnMap.get("updateTime").toString()) : null;
				String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
				returnMap.put("updateTime",updateTimeStr);

				//更新时间-用于校验时效性
				map.put("time",updateTimeStr);

				//格式化时间
				Long billDate = returnMap.get("billDate") != null ? Long.parseLong(returnMap.get("billDate").toString()) : null;
				String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
				returnMap.put("billDate",billDateStr);

				returnList.add(returnMap);
			}
		}

		int count = 0;
		map.put("page",0);
		map.put("limit",0);
		List<EaLoanbill> list2 = eaLoanbillMapper.selectLoanBills(map);
		count = list2.size();
		Map<String,Object> returnMap = new HashMap<String,Object>();
		returnMap.put("records",returnList);
		returnMap.put("total",count);
		return returnMap;
	}

	//查询借款单详情
	@Override
	public Map<String, Object> selectById(String id) {
		//查询借款单详情
		Map<String,Object> queryWrapper = new HashMap<String,Object>();
		queryWrapper.put("id",id);  //借款单id
		queryWrapper.put("page",0);
		queryWrapper.put("limit",0);
		List<EaLoanbill> eaBillsList = eaLoanbillMapper.selectLoanBills(queryWrapper);
		Map<String,Object> returnMap = new HashMap<String,Object>();
		if(eaBillsList != null && eaBillsList.size() > 0){
			EaLoanbill eaLoanbill = eaBillsList.get(0);
			returnMap = JSON.parseObject(JSON.toJSONString(eaLoanbill, SerializerFeature.WriteMapNullValue), Map.class);

			BigDecimal loanAmount = eaLoanbill.getLoanAmount() != null ? eaLoanbill.getLoanAmount() : new BigDecimal(0);
			String loanAmountStr = ConvertUpMoneyUtil.toChinese(String.valueOf(loanAmount));
			returnMap.put("loanAmount_cn",loanAmountStr);    //借款金额

			//格式化时间
			Long createTime = returnMap.get("createTime") != null ? Long.parseLong(returnMap.get("createTime").toString()) : null;
			String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
			returnMap.put("createTime",createTimeStr);

			//格式化时间
			Long updateTime = returnMap.get("updateTime") != null ? Long.parseLong(returnMap.get("updateTime").toString()) : null;
			String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
			returnMap.put("updateTime",updateTimeStr);

			//更新时间-用于校验时效性
			returnMap.put("time",updateTimeStr);

			//格式化时间
			Long billDate = returnMap.get("billDate") != null ? Long.parseLong(returnMap.get("billDate").toString()) : null;
			String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
			returnMap.put("billDate",billDateStr);

			//添加图片
			String picture = returnMap.get("picture") != null ? returnMap.get("picture").toString() : "";
			List<Map<String,Object>> fileList = GetUrlUtil.getUrl(picture,fileurl);

			//添加图片fileList
			returnMap.put("fileList",fileList);
		}
		return returnMap;
	}

	@Override
	@Transactional
	public Map<String, Object> audit(EaTaskVo eaTaskVo) {
		Map<String,Object> returnMap = new HashMap<String,Object>();
		String id = EmptyUtil.checkNull(eaTaskVo.getId());   //单据id
//        String auditManId = EmptyUtil.checkNull(eaTaskVo.getAuditManId());   //审批人id
//        String auditMan = EmptyUtil.checkNull(eaTaskVo.getAuditMan());   //审批人
		String auditComment = EmptyUtil.checkNull(eaTaskVo.getAuditComment());   //审批意见
		String status = EmptyUtil.checkNull(eaTaskVo.getStatus());   //单据状态:2通过,3退回

		//获取差旅费报销单-更新状态
		EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(id);
		eaLoanbill.setState(Integer.parseInt(status));
		eaLoanbillMapper.updateById(eaLoanbill);

		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("form_id",eaLoanbill.getId());
		List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap);
		if(eaTaskList != null && eaTaskList.size() > 0){
			EaTask eaTask = eaTaskList.get(0);
			//eaTask.setAuditManId(auditManId);
			//eaTask.setAuditMan(auditMan);
			eaTask.setAuditComment(auditComment);
			eaTask.setStatus(status);

			try {
				if(status.equals("3") || status.equals("2")){
					eaTask.setFinishTime(new Date());   //完成时间
				}
				eaTask.setAuditTime(new Date());    //审批时间
				eaTaskMapper.updateById(eaTask);

				returnMap.put("code","0");
				returnMap.put("message","审核成功!");
				return returnMap;
			}catch (Exception e){
				returnMap.put("code","-1");
				returnMap.put("message","系统异常,审核失败!");
				return returnMap;
			}
		}else{
			returnMap.put("code","-1");
			returnMap.put("message","待办不存在!");
			return returnMap;
		}
	}

	@Override
	public EaLoanbill selectByLoanId(String id) {
		EaLoanbill eaLoanbill = eaLoanbillMapper.selectByLoanId(id);
		return eaLoanbill;
	}

}
